package com.ruoyi.flowable.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.flowable.domain.Endbilltrace;
import com.ruoyi.flowable.domain.dto.FlowCommentDto;
import com.ruoyi.flowable.domain.dto.FlowTaskDto;
import com.ruoyi.flowable.domain.dto.FlowViewerDto;
import com.ruoyi.flowable.factory.FlowServiceFactory;
import com.ruoyi.flowable.service.ISysDeployFormService;
import com.ruoyi.system.domain.SysForm;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.task.Comment;
import org.flowable.identitylink.api.history.HistoricIdentityLink;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.flowable.mapper.EndedBillMapper;
import com.ruoyi.flowable.domain.EndedBill;
import com.ruoyi.flowable.service.IEndedBillService;

import javax.annotation.Resource;

/**
 * 已完成的工作票Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-25
 */
@Service
@Slf4j
public class EndedBillServiceImpl extends FlowServiceFactory implements IEndedBillService
{
    @Autowired
    private EndedBillMapper endedBillMapper;

    @Autowired
    private com.ruoyi.flowable.mapper.EndbilltraceMapper endbilltraceMapper;

    @Resource
    private ISysUserService sysUserService;


    @Resource
    private ISysRoleService sysRoleService;


    @Resource
    private ISysDeployFormService sysInstanceFormService;



    /**
     * 查询已完成的工作票
     *
     * @param workId 已完成的工作票ID
     * @return 已完成的工作票
     */
    @Override
    public EndedBill selectEndedBillById(Long workId)
    {
        return endedBillMapper.selectEndedBillById(workId);
    }

    /**
     * 查询已完成的工作票列表
     *
     * @param endedBill 已完成的工作票
     * @return 已完成的工作票
     */
    @Override
    public List<EndedBill> selectEndedBillList(EndedBill endedBill)
    {

        return endedBillMapper.selectEndedBillList(endedBill);
    }

    /**
     * 新增已完成的工作票
     *
     * @param endedBill 已完成的工作票
     * @return 结果
     */
    @Override
    public int insertEndedBill(EndedBill endedBill)
    {
        return endedBillMapper.insertEndedBill(endedBill);
    }

    /**
     * 修改已完成的工作票
     *
     * @param endedBill 已完成的工作票
     * @return 结果
     */
    @Override
    public int updateEndedBill(EndedBill endedBill)
    {
        return endedBillMapper.updateEndedBill(endedBill);
    }

    /**
     * 批量删除已完成的工作票
     *
     * @param workIds 需要删除的已完成的工作票ID
     * @return 结果
     */
    @Override
    public int deleteEndedBillByIds(Long[] workIds)
    {
        return endedBillMapper.deleteEndedBillByIds(workIds);
    }

    /**
     * 删除已完成的工作票信息
     *
     * @param workId 已完成的工作票ID
     * @return 结果
     */
    @Override
    public int deleteEndedBillById(Long workId)
    {
        return endedBillMapper.deleteEndedBillById(workId);
    }


    /**
     * 构造流程图轨迹
     * @param endedBill 已完成的工作票
     * @return
     */
    @Override
    public List<Endbilltrace> selectEndedBillTraceList(EndedBill endedBill)
    {
        int ColorFlag=0;//区分已执行的活动和未执行的活动
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日HH:mm:ss");
        Endbilltrace endbilltrace=new Endbilltrace();
        endbilltrace.setMainBizKey(endedBill.getWorkSheetCode());
        List<Endbilltrace> list=endbilltraceMapper.selectEndbilltraceList(endbilltrace);
//        list.sort(Comparator.comparing(Endbilltrace::getActivityId));
        List<Long> flowList=new ArrayList<Long>();
        Long activityId = null;
        for (Endbilltrace item:list){
            if (!flowList.contains(item.getFlowId())){
                flowList.add(item.getFlowId());
            }
            activityId=item.getActivityId();
        }
        String flowStr="";
        int flag=0;
        for(Long item:flowList){
            if (flag==0){
                flowStr+=item.toString();
                flag++;
            }else {
                flowStr+="-"+item.toString();
            }
        }
        return list;
    }




    public AjaxResult readXml(EndedBill endedBill) throws IOException {
        //根据flowstr和activityid在process_worksheet查询出对应的deploymentid
//根据对应的deploymentid去得到对应的流程图
        int ColorFlag=0;//区分已执行的活动和未执行的活动
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日HH:mm:ss");
        Endbilltrace endbilltrace=new Endbilltrace();
        endbilltrace.setMainBizKey(endedBill.getWorkSheetCode());
        List<Endbilltrace> list=endbilltraceMapper.selectEndbilltraceList(endbilltrace);
//        list.sort(Comparator.comparing(Endbilltrace::getActivityId));
        List<Long> flowList=new ArrayList<Long>();
        Long activityId = null;
        for (Endbilltrace item:list){
            if (!flowList.contains(item.getFlowId())){
                flowList.add(item.getFlowId());
            }
            activityId=item.getActivityId();
        }
        String flowStr="";
        int flag=0;
        for(Long item:flowList){
            if (flag==0){
                flowStr+=item.toString();
                flag++;
            }else {
                flowStr+="-"+item.toString();
            }
        }
        try{
            String deploymentId = endedBillMapper.readXml(flowStr, activityId);
            ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
            InputStream inputStream = repositoryService.getResourceAsStream(definition.getDeploymentId(), definition.getResourceName());
            String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            return AjaxResult.success("", result);//xml文件
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return  null;

    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Override
    public InputStream readImage(String deployId) {

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        //获得图片流
        DefaultProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //输出为图片
        return diagramGenerator.generateDiagram(
                bpmnModel,
                "png",
                Collections.emptyList(),
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体",
                null,
                1.0,
                false);
    }

//    /**
//     * 获取流程执行过程
//     *
//     * @param procInsId
//     * @return
//     */
//    @Override
//    public AjaxResult getFlowViewer(String procInsId) {
//        List<FlowViewerDto> flowViewerList = new ArrayList<>();
//        FlowViewerDto flowViewerDto;
//        // 获取流程历史中已执行节点，并按照节点在流程中执行先后顺序排序
//        List<HistoricActivityInstance> hisActIns = historyService.createHistoricActivityInstanceQuery()
//                // 过滤条件   根据流程实例编号
//                .processInstanceId(procInsId)
//                .orderByHistoricActivityInstanceStartTime()
//                // 排序条件
//                // 执行查询
//                .asc().list();
//        for (HistoricActivityInstance activityInstance : hisActIns) {
//            //                                          活动类型
//            if (!"sequenceFlow".equals(activityInstance.getActivityType())) {  //sequenceFlow顺序流，是连接两个流程节点的连线
//                flowViewerDto = new FlowViewerDto();
//                flowViewerDto.setKey(activityInstance.getActivityId());
//                flowViewerDto.setCompleted(!Objects.isNull(activityInstance.getEndTime()));//结束时间不为空说明已经完成
//                flowViewerList.add(flowViewerDto);
//            }
//        }
//        return AjaxResult.success(flowViewerList);
//    }

//    /**
//     * 流程完成时间处理
//     *
//     * @param ms
//     * @return
//     */
//    private String getDate(long ms) {
//
//        long day = ms / (24 * 60 * 60 * 1000);
//        long hour = (ms / (60 * 60 * 1000) - day * 24);
//        long minute = ((ms / (60 * 1000)) - day * 24 * 60 - hour * 60);
//        long second = (ms / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60);
//
//        if (day > 0) {
//            return day + "天" + hour + "小时" + minute + "分钟";
//        }
//        if (hour > 0) {
//            return hour + "小时" + minute + "分钟";
//        }
//        if (minute > 0) {
//            return minute + "分钟";
//        }
//        if (second > 0) {
//            return second + "秒";
//        } else {
//            return 0 + "秒";
//        }
//    }

}
